import {
  getUser,
  getRoles,
  getMenu,
  getToken,
  getRefreshToken,
  removeUserInfo,
  setUserInfo
} from '@/utils/auth'
import { resetRouter } from '@/router'

const user = getUser()
const roles = getRoles()

const menu = getMenu()

const token = getToken()
const refreshToken = getRefreshToken()

export default {
  state: {
    user,
    roles,
    menu,
    token,
    refreshToken
  },
  getters: {
    user: state => state.user,
    roles: state => state.roles,
    menu: state => state.menu,
    token: state => state.token,
    refreshToken: state => state.refreshToken,
    userInfo: state => {
      return {
        userNo: state.user.userNo,
        userName: state.user.userName
      }
    }
  },
  mutations: {
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
    },
    SET_ROLE: (state, roles) => {
      state.roles = roles
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      state.refreshToken = refreshToken
    }
  },

  actions: {
    /**
     * 登录
     * @param {*} param0
     * @param {} data { user, menu, auth }
     */
    Login ({ commit }, { user = {}, roles = {}, menu = [], auth = { accessToken: '', refreshToken: '' } }) {
      commit('SET_USER', user)
      commit('SET_ROLE', roles)
      commit('SET_MENU', menu)
      commit('SET_TOKEN', auth.accessToken)
      commit('SET_REFRESH_TOKEN', auth.refreshToken)

      // setUserInfo({
      //   user: user,
      //   roles,
      //   menu: menu,
      //   accessToken: auth.accessToken,
      //   refreshToken: auth.refreshToken
      // })
    },

    /**
     * 登出
     * @param {*} param0
     */
    LogOut ({ commit }) {
      commit('SET_USER', {})
      commit('SET_ROLE', {})
      commit('SET_MENU', [])
      commit('SET_TOKEN', '')
      commit('SET_REFRESH_TOKEN', '')
      resetRouter()
      removeUserInfo()
    }
  }
}
